package com.sean.gulimall.product.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sean.common.utils.PageUtils;
import com.sean.common.utils.Query;
import com.sean.gulimall.product.dao.CategoryDao;
import com.sean.gulimall.product.entity.CategoryBrandRelationEntity;
import com.sean.gulimall.product.entity.CategoryEntity;
import com.sean.gulimall.product.service.CategoryBrandRelationService;
import com.sean.gulimall.product.service.CategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


@Service("categoryService")
public class CategoryServiceImpl extends ServiceImpl<CategoryDao, CategoryEntity> implements CategoryService {

    @Autowired
    private CategoryBrandRelationService categoryBrandRelationService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<CategoryEntity> page = this.page(
                new Query<CategoryEntity>().getPage(params),
                new QueryWrapper<CategoryEntity>()
        );

        return new PageUtils(page);
    }


    /**
     * 获取树形结构的商品数据
     * @return
     */
    @Override
    public  List<CategoryEntity> listWithTree() {
        //1.获取所有的商品分类数据
        List<CategoryEntity> rootCategoryList = baseMapper.selectList(null);
        //2.组装成父子树形结构
        List<CategoryEntity> list = rootCategoryList.stream()
                //过滤出一级分类商品
                .filter(categoryEntity -> categoryEntity.getParentCid().longValue() == 0 )
                .map(categoryEntity -> {
                    categoryEntity.setChildren(getChildren(categoryEntity,rootCategoryList));
                    return categoryEntity;
                })
                .sorted((menu1,menu2)->{return  (menu1.getSort()==null ? 0 : menu1.getSort()) -
                        (menu2.getSort() == null?0:menu2.getSort());})
                .collect(Collectors.toList());
        return list;
    }

    /**
     * 递归查询出所有的子菜单
     * @param root
     * @param allCategories
     * @return
     */
    private List<CategoryEntity> getChildren(CategoryEntity root,List<CategoryEntity> allCategories)
    {
        List<CategoryEntity> children = allCategories.stream()
                .filter(categoryEntity -> categoryEntity.getParentCid().longValue() == root.getCatId().longValue())
                .map(categoryEntity -> {
                    categoryEntity.setChildren(getChildren(categoryEntity, allCategories));
                    return categoryEntity;
                }) .sorted((menu1, menu2) -> {
                    return (menu1.getSort()==null ? 0 : menu1.getSort())  -
                            (menu2.getSort() == null?0:menu2.getSort());})
                .collect(Collectors.toList());
        return children;
    }

    @Override
    public void removeCategoryByIds(List<Long> asList) {
        //todo 需要判断删除的菜单是否还有子菜单
        baseMapper.deleteBatchIds(asList);
    }

    @Override
    public Long[] getCategoryPath(Long catelogId) {
        List<Long> path = new ArrayList<>();
        List<Long> parentPath = this.getCategoryIds(catelogId,path);
        Collections.reverse(parentPath);
        return parentPath.toArray(new Long[parentPath.size()]);
    }

    /**
     * 递归调用封装分类id
     * @param catelogId
     * @param path
     * @return
     */
    private List<Long> getCategoryIds(Long catelogId,List<Long> path)
    {
        //首先把自己的分类id存入路径path中
        path.add(catelogId);
        CategoryEntity categoryEntity = this.getById(catelogId);
        if(categoryEntity.getParentCid() != 0)
        {
            getCategoryIds(categoryEntity.getParentCid(),path);
        }
        return path;
    }

    @Transactional(rollbackFor = {Exception.class})
    @Override
    public void updateDetailById(CategoryEntity category) {
        //更新分类
        this.updateById(category);
        //更新关联表
        CategoryBrandRelationEntity relationEntity = new CategoryBrandRelationEntity();
        relationEntity.setCatelogName(category.getName());

        LambdaUpdateWrapper<CategoryBrandRelationEntity> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(CategoryBrandRelationEntity::getCatelogId,category.getCatId());

        categoryBrandRelationService.update(relationEntity,updateWrapper);
    }
}
